package com.leetcode.LC_MED;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class LC39_2 {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {

        ArrayList<List<Integer>> lists = new ArrayList<>();
        dfs(candidates, target, lists, new ArrayList<>());
        return lists;

    }

    private void dfs(int[] candidates, int target, List<List<Integer>> lists, List<Integer> list) {
        //剪枝
        int sum = 0;
        for (Integer integer : list) {
            sum += integer;
        }
        if (target == sum) {
            //多一步数组排序
            ArrayList<Integer> list1 = new ArrayList<>(list);
            Collections.sort(list1);
            if (!lists.contains(list1)) {
                lists.add(list1);
            }
            return;
        } else if (target < sum) {
            return;
        }
        //结点
        for (int i = 0; i < candidates.length; i++) {
            list.add(candidates[i]);
            dfs(candidates, target, lists, list);
            list.remove(list.size() - 1);
        }
    }

    public static void main(String[] args) {
        for (List<Integer> list : new LC39_2().combinationSum(new int[]{1,2}, 4)) {
            for (Integer integer : list) {
                System.out.print(integer + ",");
            }
            System.out.println();
        }
    }
}
